package com.CST.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.CST.common.api.ResultObject;
import com.CST.dto.DateDTO;
import com.CST.entity.*;
import com.CST.mapper.cst.EtlSalaryMapper;
import com.CST.service.IBdEnumdetailService;
import com.CST.service.IBdSysUserService;
import com.CST.service.ICusDutyfactorService;
import com.CST.service.IEtlSalaryService;
import com.CST.vo.SalaryDetailByAccIdVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ly
 * @since 2022-01-24
 */
@Service
public class EtlSalaryServiceImpl extends ServiceImpl<EtlSalaryMapper, EtlSalary> implements IEtlSalaryService {

    @Autowired
    private IBdEnumdetailService bdEnumdetailService;

    @Autowired
    private ICusDutyfactorService cusDutyfactorService;
    
    @Autowired
    private EtlSalaryMapper etlSalaryMapper;


    @Override
    public ResultObject getEtlSalarySource(EtlSalary entity) {
        if (entity.getYear() == null || entity.getYear().isEmpty()) {
            return ResultObject.errorReturn("薪酬数据未能获取年份,请联系管理员");
        }
        if (entity.getMonth() == null || entity.getMonth().isEmpty()) {
            return ResultObject.errorReturn("薪酬数据未能获取月份,请联系管理员");
        }
        //取查询时间的年
        entity.setTableName("ETL_SALARY_" + entity.getYear());
        List<EtlSalary> list = baseMapper.getEtlSalarySource(entity);
        return ResultObject.successReturn(list);
    }

    @Override
    public ResultObject getEtlSalaryPageSource(EtlSalary entity) {
        if (entity.getYear() == null || entity.getYear().isEmpty()) {
            return ResultObject.errorReturn("薪酬数据未能获取年份,请联系管理员");
        }
        if (entity.getMonth() == null || entity.getMonth().isEmpty()) {
            return ResultObject.errorReturn("薪酬数据未能获取月份,请联系管理员");
        }
        List<CostDataInfo> retList = new ArrayList<>();
        try {


            List<CostDataInfo> lstCostData = new ArrayList<>();
            //取查询时间的年
            entity.setTableName("ETL_SALARY_" + entity.getYear());
            //1.获取选择年月的薪酬数据
            long startTime = System.currentTimeMillis();
            List<EtlSalary> lstSalary = baseMapper.getEtlDeptSalarySource(entity);
            long endTime = System.currentTimeMillis();
            System.out.println("程序运行时间：" + (endTime - startTime) + "ms");//输出程序运行时间

            /*(后续这块要改,要从HIS中拿数据) Start */

            //3.计算出所选科室的所有成员
            List<String> lstAllEmp = lstSalary.stream().map(t -> t.getEmpId()).collect(Collectors.toList());

            //4.获取选择年月的配置分摊系数(人员)
            CusDutyfactor searchCusDutyfactor = new CusDutyfactor();
            searchCusDutyfactor.setYear(entity.getYear());
            searchCusDutyfactor.setMonth(entity.getMonth());
            searchCusDutyfactor.setLstDept(entity.getLstDept());
            List<CusDutyfactor> lstCusDutyFactor = cusDutyfactorService.selectworkfactor(searchCusDutyfactor);
            //已配置分摊系数人员
            List<String> lstSetEmp = lstCusDutyFactor.stream().map(t -> t.getEmployeecode()).collect(Collectors.toList());

            //根据3.  4.过滤出未配置分摊系数的人员
            List<String> lstNoSetEmp = lstAllEmp.stream().filter(t -> !lstSetEmp.contains(t)).collect(Collectors.toList());


            /*(后续这块要改,要从HIS中拿数据) END */

            // 已配置分摊系数数据,正常赋值
            List<EtlSalary> lstSetSalary = lstSalary.stream().filter(t -> lstSetEmp.contains(t.getEmpId())).collect(Collectors.toList());
            lstSetSalary.forEach(item -> {
                CusDutyfactor matchInfo = lstCusDutyFactor.stream().filter(t -> item.getEmpId().equals(t.getEmployeecode())
                        && item.getDeptId().equals(t.getDeptcode())).findFirst().orElse(null);
                if (null != matchInfo) {
                    CostDataInfo costDataInfo = new CostDataInfo();
                    costDataInfo.setYear(item.getYear());
                    costDataInfo.setMonth(item.getMonth());
                    costDataInfo.setOperDime("");
                    costDataInfo.setDeptCode(item.getDeptId());
                    costDataInfo.setDeptName(item.getDeptName());
                    costDataInfo.setAmount(item.getAmount() * Double.parseDouble(matchInfo.getRulecode()));
                    costDataInfo.setCostItemCode(item.getCostItemCode());
                    costDataInfo.setCostItemName(item.getCostItemName());
                    costDataInfo.setDeptTypeId(item.getDeptTypeId());
                    costDataInfo.setDeptTypeName(item.getDeptTypeName());
                    costDataInfo.setUnitCode(item.getUnitCode());
                    costDataInfo.setUnitName(item.getUnitName());
                    costDataInfo.setYard(item.getYard());
                    lstCostData.add(costDataInfo);
                }
            });

            //未配置分摊系数

            List<EtlSalary> lstNoSetSalary = lstSalary.stream().filter(t -> lstNoSetEmp.contains(t.getEmpId())).collect(Collectors.toList());
            lstNoSetSalary.forEach(item -> {
                CostDataInfo costDataInfo = new CostDataInfo();
                costDataInfo.setYear(item.getYear());
                costDataInfo.setMonth(item.getMonth());
                costDataInfo.setOperDime("");
                costDataInfo.setDeptCode(item.getDeptId());
                costDataInfo.setDeptName(item.getDeptName());
                costDataInfo.setCostItemCode(item.getCostItemCode());
                costDataInfo.setCostItemName(item.getCostItemName());
                costDataInfo.setDeptTypeId(item.getDeptTypeId());
                costDataInfo.setDeptTypeName(item.getDeptTypeName());
                costDataInfo.setUnitCode(item.getUnitCode());
                costDataInfo.setUnitName(item.getUnitName());
                costDataInfo.setYard(item.getYard());
                if(("1").equals(item.getIsSame())){
                    costDataInfo.setAmount(item.getAmount());
                } else {
                    costDataInfo.setAmount(0d);
                }
                lstCostData.add(costDataInfo);
            });


            Map<String, List<CostDataInfo>> groupList = lstCostData.stream().collect(Collectors.groupingBy(t -> t.getDeptCode() + "-" + t.getCostItemCode()));

            Iterator<String> it = groupList.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                List<CostDataInfo> keyList = groupList.get(key);
                CostDataInfo newInfo = new CostDataInfo();
                //拷贝属性
                BeanUtil.copyProperties(keyList.get(0), newInfo);
                newInfo.setAmount(keyList.stream().mapToDouble(t -> t.getAmount()).sum());
                retList.add(newInfo);
            }
        } catch (Exception ex) {
            int a =0;
        }
        return ResultObject.successReturn(retList);
    }

    /**
     * 获取所有父级科室人员经费详情
     * 按照所有父级科室账套分组
     * @param dateDTO
     * @return
     */
    @Override
    public List<SalaryDetailByAccIdVO> listPersonalSalaryDetail(DateDTO dateDTO,String pDeptCode) {
        List<SalaryDetailByAccIdVO> salaryDetailByAccIdVOList = etlSalaryMapper.listPersonalSalaryDetail(dateDTO, pDeptCode);
        return salaryDetailByAccIdVOList;
    }

    private static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE);
    }
}
